package com.zx.security.filter;

import com.zx.security.security.TokenManger;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class TokenAuthFilter extends BasicAuthenticationFilter {
    @Resource
    private TokenManger tokenManger;
    @Resource
    private RedisTemplate redisTemplate;


    public TokenAuthFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
      //获取当前认证用户权限信息
        UsernamePasswordAuthenticationToken authentication = getAuthentication(request);

        if (authentication!=null){
           SecurityContextHolder.getContext().setAuthentication(authentication);
        }

        chain.doFilter(request,response);

    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request){


        String token = request.getHeader("token");
        if (token!=null){
            String tokenInformation = tokenManger.getTokenInformation(token);
            List<String> permissionList= (List<String>)redisTemplate.opsForValue().get(tokenInformation);
            Collection<GrantedAuthority> authorities = new ArrayList<>();
             for (String p :permissionList){
                 SimpleGrantedAuthority authority = new SimpleGrantedAuthority(p);
                 authorities.add(authority);
             }

            return new UsernamePasswordAuthenticationToken(tokenInformation,token,authorities);
        }
      return  null;
    }
}
